/*
 * File     : DebugAllocator.java
 * Created  : 26 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import com.googlecode.dni.Allocator;
import com.googlecode.dni.DirectNativeInterface;
import com.googlecode.dni.internal.structure.AbstractStructureFactory;
import com.googlecode.dni.type.Pointer;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;


/**
 * Implementation that logs allocations.
 *
 * @author Matthew Wilson
 */
final class DebugAllocator implements Allocator
{

    private static final Logger LOGGER = Logger.getLogger( "DNI.Allocator" );

    private static final String CLASS_NAME = DebugAllocator.class.getName();

    private static final String ABSTRACT_STRUCTURE_FACTORY = AbstractStructureFactory.class.getName();

    private static final Set< String > IGNORED_CLASS_NAME = new HashSet< String >( Arrays.asList( new String[]
    {
        CLASS_NAME,
        DniInternal.class.getName(),
        DirectNativeInterface.class.getName(),
        ABSTRACT_STRUCTURE_FACTORY,
        "com.googlecode.dni.internal.structure.StructureList",
        PointerList.class.getName()
    } ) );


    private final Allocator allocator;

    private final Map< Pointer, String > pointers = new ConcurrentHashMap< Pointer, String >();


    /**
     * @param allocator
     *            the delegate allocator
     */
    DebugAllocator( final Allocator allocator )
    {
        this.allocator = allocator;

        Thread thread = new Thread( new DebugAllocatorTidyTask(), "DebugAllocatorTidy" );
        Runtime.getRuntime().addShutdownHook( thread );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Pointer allocate( final long size )
    {
        LOGGER.info( "Allocating " + size + " bytes" );

        if ( size <= 0 )
        {
            throw new AssertionError( size );
        }

        Pointer pointer = this.allocator.allocate( size );

        recordAllocation( pointer );

        LOGGER.info( "Allocated " + size + " bytes at " + pointer );

        return pointer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Pointer copy( final Pointer sourcePointer, final long size )
    {
        LOGGER.info( "Copy-allocating " + size + " bytes" );

        Pointer pointer = this.allocator.copy( sourcePointer, size );

        recordAllocation( pointer );

        LOGGER.info( "Copy-allocated " + size + " bytes at " + pointer );

        return pointer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void free( final Pointer pointer )
    {
        LOGGER.info( "Freeing " + pointer );

        Object existing = this.pointers.remove( pointer );
        if ( existing == null )
        {
            throw new AssertionError( "Double-free found: " + pointer );
        }

        this.allocator.free( pointer );
    }

    private void recordAllocation( final Pointer pointer )
    {
        String previous = this.pointers.put( pointer, locateOwner() );
        if ( previous != null )
        {
            LOGGER.warning( "Reallocating same pointer; was memory freed via native code? " + pointer + " " + previous );
        }
    }

    private static String locateOwner()
    {
        // this method isn't quick; but it's for debugging only

        StackTraceElement[] stackTrace = new Throwable().getStackTrace();
        int i = 0;

        // find the first occurrence of this class
        for ( ; i < stackTrace.length; i++ )
        {
            if ( CLASS_NAME.equals( stackTrace[ i ].getClassName() ) )
            {
                i++;
                break;
            }
        }

        // find the first class that is not this class or DniInternal
        for ( ; i < stackTrace.length; i++ )
        {
            String className = stackTrace[ i ].getClassName();
            if ( !IGNORED_CLASS_NAME.contains( className ) )
            {
                break;
            }
        }

        if ( i >= stackTrace.length )
        {
            return "<unknown>";
        }

        // special case for structure types
        StackTraceElement element = stackTrace[ i ];
        if ( i < stackTrace.length - 1
             && element.getLineNumber() < 0
             && "<init>".equals( element.getMethodName() ) )
        {
            i++;
            for ( ; i < stackTrace.length; i++ )
            {
                StackTraceElement candidate = stackTrace[ i ];
                if ( !"allocateUntyped".equals( candidate.getMethodName() )
                     && !ABSTRACT_STRUCTURE_FACTORY.equals( candidate.getClassName() )
                     && !"copy".equals( candidate.getMethodName() ) )
                {
                    element = candidate;
                    break;
                }
            }
        }

        return element.toString();
    }

    @SuppressFBWarnings( value = { "DM_GC", "MDM_RUNFINALIZATION" },
                         justification = "It's only for debugging" )
    private final class DebugAllocatorTidyTask implements Runnable
    {
        @Override
        public void run()
        {
            // Allow any AutoFrees to do their job
            System.gc();
            System.runFinalization();

            for ( Map.Entry< Pointer, String > entry : DebugAllocator.this.pointers.entrySet() )
            {
                System.err.println( "Exiting without freeing memory: " + entry.getKey() + " from " + entry.getValue() );
            }
        }
    }

}
